package com.ruoyi.web.controller.system;

import java.util.*;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 客户Controller
 * 
 * @author ruoyi
 * @date 2019-10-14
 */
@Controller
@RequestMapping("/system/customer")
public class CustomerController extends BaseController
{
    private String prefix = "system/customer";

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IRelationshipRecordService relationshipRecordService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IShareService shareService;

    @RequiresPermissions("system:customer:view")
    @GetMapping()
    public String customer()
    {
        return prefix + "/customer";
    }

    /**
     * 查询客户列表
     */
    @RequiresPermissions("system:customer:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Customer customer)
    {
        startPage();
        List<Customer> list = customerService.selectCustomerList(customer);
        for(Customer cus:list){
            if(cus.getMemberId()!=null && !cus.getMemberId().toString().equals("")){
                Member memeber = memberService.selectMemberById(cus.getMemberId());
                if(memeber!=null){
                    cus.setMemberName(memeber.getNickName());
                }
            }
            RelationshipRecord relationshipRecord = new RelationshipRecord();
            relationshipRecord.setCustomerId(cus.getId());
            List<RelationshipRecord> relationshipRecords = relationshipRecordService.selectRelationshipRecordList(relationshipRecord);
            if(relationshipRecords.size()>0){
                cus.setRecord(relationshipRecords.get(relationshipRecords.size()-1).getRelationshipResult()+"("+DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",(Date)(relationshipRecords.get(relationshipRecords.size()-1).getCreateTime()))+")");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出客户列表
     */
    @RequiresPermissions("system:customer:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Customer customer)
    {
        PageHelper.startPage(1, 99999999, "relation_time desc");
        List<Customer> list = customerService.selectCustomerList(customer);
        for(Customer cus:list){
            if(cus.getMemberId()!=null && !cus.getMemberId().toString().equals("")){
                Member member = memberService.selectMemberById(cus.getMemberId());
                if(member!=null){
                    cus.setMemberName(member.getNickName());
                }
            }
        }
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        return util.exportExcel(list, "customer");
    }

    /**
     * 新增客户
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存客户
     */
    @RequiresPermissions("system:customer:add")
    @Log(title = "客户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Customer customer)
    {
        Customer customerTemp = new Customer();
        if(customer.getTelephone()!=null && !customer.getTelephone().equals("")){
            String[] telephones = customer.getTelephone().split(";");
            for(String telephone: telephones){
                customerTemp.setTelephone(telephone);
                List<Customer> cuss = customerService.selectCustomerList(customerTemp);
                if(cuss.size()>0){
                    return toAjax(0);
                }
            }
        }else{
            return toAjax(0);
        }
        customer.setRelationTime(DateUtils.getNowDate());
        return toAjax(customerService.insertCustomer(customer));
    }

    /**
     * 修改客户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Customer customer = customerService.selectCustomerById(id);
        if(customer.getMemberId()!=null && !customer.getMemberId().toString().equals("")){
            Member member = memberService.selectMemberById(customer.getMemberId());
            if(member!=null){
                customer.setMemberName(member.getNickName());
            }
        }
        mmap.put("customer", customer);
        return prefix + "/edit";
    }

    /**
     * 修改保存客户
     */
    @RequiresPermissions("system:customer:edit")
    @Log(title = "客户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Customer customer)
    {
        Customer selectCustomerById = customerService.selectCustomerById(customer.getId());
        Customer customerTemp = new Customer();
        if(customer.getTelephone()!=null && !customer.getTelephone().equals("")){
            String[] telephones = customer.getTelephone().split(";");
            String[] oldTelephones = selectCustomerById.getTelephone().split(";");
            List<String> oldTelephoneList = Arrays.asList(oldTelephones);
            for(String telephone: telephones){
                if(oldTelephoneList.contains(telephone)){
                    continue;
                }
                customerTemp.setTelephone(telephone);
                List<Customer> cuss = customerService.selectCustomerList(customerTemp);
                if(!selectCustomerById.getTelephone().equals(customer.getTelephone())&&cuss.size()>0){
                    return toAjax(0);
                }
            }
        }else{
            return toAjax(0);
        }
        customer.setRelationTime(DateUtils.getNowDate());
        return toAjax(customerService.updateCustomer(customer));
    }

    /**
     * 删除客户
     */
    @RequiresPermissions("system:customer:remove")
    @Log(title = "客户", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
    	String[] idArr = ids.split(",");
    	for(String id:idArr){
        	RelationshipRecord relationshipRecord = new RelationshipRecord();
        	relationshipRecord.setCustomerId(Long.parseLong(id));
        	List<RelationshipRecord> selectRelationshipRecordList = relationshipRecordService.selectRelationshipRecordList(relationshipRecord);
        	for(RelationshipRecord rr:selectRelationshipRecordList){
            	relationshipRecordService.deleteRelationshipRecordById(rr.getId());
        	}

        	Share share = new Share();
            share.setCustomerId(Long.parseLong(id));
            List<Share> shareList = shareService.selectShareList(share);
            for(Share share1:shareList){
                shareService.deleteShareById(share1.getId());
            }
    	}

        return toAjax(customerService.deleteCustomerByIds(ids));
    }
	/**
     * 联系记录
     */
    @GetMapping("/relationshipRecord/{id}")
    public String relationshipRecord(@PathVariable("id") Long id, ModelMap mmap)
    {
        Customer customer = customerService.selectCustomerById(id);
        mmap.put("customer", customer);
        return "system/record/record";
    }

    /**
     * 客户分享
     */
    @GetMapping("/share/{id}")
    public String share(@PathVariable("id") Long id, ModelMap mmap)
    {
        Customer customer = customerService.selectCustomerById(id);
        mmap.put("customer", customer);
        return "system/customer/share";
    }

    /**
     * 选择业务员树
     */
    @GetMapping(value = { "/selectMemberTree/{id}", "/selectMemberTree/" })
    public String selectMemberTree(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        if (StringUtils.isNotNull(id))
        {
            mmap.put("member", memberService.selectMemberById(id));
        }
        return prefix + "/tree";
    }

}
